<!--
import { type } from 'os';
import { setTimeout } from 'timers';
 * @Author: your name
 * @Date: 2020-12-28 18:33:20
 * @LastEditTime: 2021-05-20 16:33:57
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \solaxcloud\src\views\test\printingSN.vue
-->
<template>
    <div class="print-sn-main-box">
        <div class="search-box">
            <div class="search-box-sub">
                <span class="lable-text">{{$t('inventoryManage.type')}}</span>
                <el-select v-model="type" filterable :placeholder="$t('pleaseSelect')" @change='typeChange'>
                    <el-option
                    v-for="item in printType"
                    :key="item.id"
                    :label="item.text"
                    :value="item.id">
                    </el-option>
                </el-select>
            </div>
            
            <div class="search-box-sub" v-if='type == 2'>
                <span class="lable-text">打印类型</span>
                <el-select v-model="typeSub" filterable :placeholder="$t('pleaseSelect')" :clearable='true' @change='changeTypeSub'>
                    <el-option
                    v-for="item in printTypeSub"
                    :key="item.id"
                    :label="item.text"
                    :value="item.id">
                    </el-option>
                </el-select>
            </div>
            <div class="search-box-sub" v-if='type == 2 && typeSub == 3'>
                <span class="lable-text">设备类型</span>
                <el-select v-model="deviceType" filterable :placeholder="$t('pleaseSelect')" :clearable='true'>
                    <el-option
                    v-for="item in deviceTypeList"
                    :key="item.value"
                    :label="item.code"
                    :value="item.value">
                    </el-option>
                </el-select>
            </div>
            <div class="search-box-sub" v-if='type == 2 && deviceType == 1'>
                <span class="lable-text">机型</span>
                <el-select v-model="inverterType" filterable :placeholder="$t('pleaseSelect')" :clearable='true'>
                    <el-option
                    v-for="item in inverterTypeData"
                    :key="item.value"
                    :label="item.code"
                    :value="item.value">
                    </el-option>
                </el-select>
            </div>
            <div class="search-box-sub" v-if='type == 2 && typeSub == 1'>
                <span class="lable-text">{{$t('version.versionAdd.partNumber')}}</span>
                <el-select v-model="inverterType" filterable :placeholder="$t('pleaseSelect')" :clearable='true' @change='inverterTypeChange'>
                    <el-option
                    v-for="item in partList"
                    :key="item.partNo"
                    :label="item.partNo"
                    :value="item.partNo">
                    </el-option>
                </el-select>
            </div>
            <!-- 其他sn sn区间 start-->
            <div class="search-box-sub" v-if='type == 2'>
                <span class="lable-text">SN范围</span>
                <el-input v-model="head" v-big style="margin-right:10px;" placeholder='请输入SN标识头' @blur="blurHead" :disabled="partNoDisabled"></el-input>
                <el-input v-model="start" placeholder="请输入起始范围" @blur="blurStart" :disabled="partNoDisabled"></el-input>
                <span>-</span>
                <el-input v-model="end" placeholder="请输入结束范围" @blur="blurEnd" :disabled="partNoDisabled"></el-input>
            </div>
            <!-- end -->
            
            <!-- 通讯模块sn 料号 start-->
            <div class="search-box-sub" v-if='type == 1'>
                <span class="lable-text">{{$t('version.versionAdd.partNumber')}}</span>
                <el-select v-model="partNo" filterable :placeholder="$t('pleaseSelect')" :clearable='true' @change='partNoChange'>
                    <el-option
                    v-for="item in textDataList"
                    :key="item.code"
                    :label="item.code"
                    :value="item.code">
                    </el-option>
                </el-select>
            </div>
            <div class="search-box-sub" v-if='type == 1'>
                <span class="lable-text">打印类型</span>
                <el-select v-model="barType" filterable :placeholder="$t('pleaseSelect')" :clearable='true' :disabled="true">
                    <el-option
                    v-for="item in barTypeList"
                    :key="item.id"
                    :label="item.text"
                    :value="item.id">
                    </el-option>
                </el-select>
            </div>
            <!-- end -->
            <div class="search-box-sub">
                <el-button type="primary" @click='connectPrint()'>{{$t('test.printing.linePrint')}}</el-button>
                <el-button type="primary" @click='print'  :disabled="disabledFlag" v-if='!continuePrintFlag && typeSub != 1'>单打</el-button>
                <el-button v-if='continuePrintFlag && typeSub != 1' type="primary" @click='continuePrint'  :disabled="disabledFlag">单打</el-button>
                <el-button type="primary" v-if='type==2' @click='printBatch' >批量打印</el-button>
                <el-button type="primary" v-if='batchFlag && type==2' @click='stopBatch' >停止批量打印</el-button>
                
                
            </div>
        </div>
        <div class="massage-box" v-if='total && type==2'>
            <span>当前范围总数：</span><span>{{total}}</span>
            <span>剩余打印总数：</span><span>{{returnSurplusTotal()}}</span>

            <span>已打印位置：</span><span>{{currentIndex?currentIndex:'无'}}</span>
            <!-- <span>任务完成状态：</span><span>{{headerMsg.finishFlag?'完成':'未完成'}}</span> -->
            
        </div>
        <el-button type="primary" v-if='type == 2'  style='margin-bottom:10px;' @click='showSupplement'>补码</el-button>
        <el-button type="primary" v-if='type == 2'  style='margin-bottom:10px;' @click='csPrint()'>测试打印</el-button>
        <a href="javascript:;" style="margin-left:10px;color:orange;" @click='$emit("update:pageFlag",true);' v-if='typeSub == 1'>设置料号与机型对应关系>></a>
        <div class="content-main-box">
            <el-card class="box-card" style="width:60%;">
                <div slot="header" class="clearfix" >
                    <i class="el-icon-printer" style="font-size: 25px;vertical-align: middle;"></i>
                    <span>打印机状态：{{status || '未连接'}}</span>
                    <span v-if='count' style="float: right; padding: 3px 0" type="text">剩余SN数量：{{count}}</span>
                </div>
                <div class="content-header">
                    <span>详细信息</span>
                </div>
                <div class="content-box">
                    <div v-for="item in printHistory" :key="item.sn" :class="item.status == 'file'? 'red':''" >
                        <span>提示信息：</span><span>{{item.sn}}</span><span> ---- ---- {{item.status == 'file'? '打印失败':'打印成功'}}</span>
                    </div>
                </div>
            </el-card>
        </div>
        <supplementModal v-if='visible' :visible.sync='visible' @csPrint='csPrint' :printTypeSub='printTypeSub' :partList='partList'></supplementModal>
    </div>
</template>

<script>
let  ws=''
let  wsUrl = 'ws://localhost:2012';
import supplementModal from './printSupplement'
import { setInterval, setTimeout } from 'timers';
export default {
    components: {
        supplementModal
    },
    props: {
        pageFlag:{
            type:Boolean,
            default:false
        }
    },
    data() {
        return {
            partNo:'',
            textDataList:[],
            status:'',
            count:'',
            barType:'',
            printHistory:[],
            csPrintFormData:{},
            partNoFlag:false,
            disabledFlag:false,
            barTypeList:[{
                id:'1',
                text:'条码'
            },{
                id:'2',
                text:'V2.0二维码'
            },{
                id:'3',
                text:'V3.0二维码'
            }],
            printType:[{
                id:'1',
                text:'通讯模块SN'
            },{
                id:'2',
                text:'其他SN'
            }],
            printTypeSub:[{
                id:'1',
                text:'机型+条码+二维码'
            },{
                id:'2',
                text:'条码+二维码'
            },{
                id:'3',
                text:'单条码'
            }],
            type:"2",
            typeSub:"",
            head:'',
            start:'',
            end:'',
            legal:true,
            inverterTypeList:[],
            inverterType:'',
            inverterTypeData:[],
            deviceTypeList:[],
            deviceType:'',
            currentIndex:'',
            inverterTypeSet:'',
            headerMsg:{},
            id:'',
            continuePrintFlag:false,
            batchFlag:false,
            timeId:'',
            visible:false,
            partNoDisabled:false,
            partList:[]
        };
    },
    computed: {
        total(){
            return parseInt(this.end)-parseInt(this.start) + 1
        },
    },
    watch: {
        head:{
            handler(nv,ov){
                this.start = ''
                this.end = ''
            },
            deep:true
        },
    },
    created() {
        
    },
    activated() {
        this.prtsettingGetPage()
        console.log("激活activated钩子函数");
    },
    mounted() {

        if(localStorage.getItem('printType')){
            this.type = localStorage.getItem('printType')
        }
        let that = this
        if(this.$route){

        }
        document.onkeydown = function(e){
            // console.log(that.$route.fullPath == "/printingSN");
            if(e.keyCode == 13 && that.$route.fullPath == "/printingSN"){
                // alert("回车键事件触发~");
                that.print()
            }
        }
        this.getDictionaryBatch()
    },
    methods: {
        async prtsettingGetPage(){
            let res = await this.API.prtsettingGetPage({
                partNo:'',
                type:'',
                inverterType:'',
                size:1000,
                current:1
            })
            this.partList = res.rows
        },
        async prtTaskDelete(){
            let resTask = await this.API.prtTaskDelete({
                prefix:this.head
            })
            if(resTask.success){
                this.comm.showMsg(true,'取消当前SN标头的任务成功！')
            }else{
                this.comm.showMsg(false,'未知错误，取消当前SN标头的任务失败！请联系管理员！')
            }
        },
        partNoChange(){
            let type = this.comm.returnCode(this.textDataList,this.partNo,'code','remark')
            if(type == '1'){
                this.barType = '1'
            }else if(type == '2'){
                this.barType = '2'
            }else if(type == '3'){
                this.barType = '3'
            }else{
                this.barType = ''
            }

        },
        csPrint(formData){
            console.log(formData,'formData');
            this.csPrintFormData = formData
            if(!formData){
                if(!this.partNoFlag){
                    this.comm.showMsg(false,'请先连接打印机')
                    return
                }
                if(!this.legal){
                    this.comm.showMsg(false,'请输入合法的标识头(SN长度不得大于12小于10)')
                    return
                }
                if(this.start == '' ){
                    this.comm.showMsg(false,'请先填写起始范围')
                    return 
                }
                if(this.end == '' ){
                    this.comm.showMsg(false,'请先结束范围')
                    return 
                }
            }else{
                if(!this.partNoFlag){
                    this.comm.showMsg(false,'检测到未连接打印机，系统自动连接打印机中')
                    this.connectPrint(true)
                }
            }

            let sn = this.head + this.returnStringNum(this.start)
            let type = this.typeSub
            if(formData){
                sn = formData.sn
                type = formData.type
            }
            setTimeout(()=>{
                if(formData){
                    if(type == 1){
                        this.typeBarQR(sn,true)
                    }else if(type == 2){
                        this.BarQR(sn,true)
                    }else if(type == 3){
                        this.Bar(sn,true)
                    }
                }else{
                    if(type == 1){
                        this.typeBarQR(sn,false)
                    }else if(type == 2){
                        this.BarQR(sn,false)
                    }else if(type == 3){
                        this.Bar(sn,false)
                    }
                }
            },500)
        },
        showSupplement(){
            this.visible = true
        },
        returnSurplusTotal(){
            if(this.currentIndex){
                if(this.currentIndex<parseInt(this.start)){
                    return this.total
                }else{
                   return parseInt(this.end)-this.currentIndex
                }
            }else{
                return this.total
            }
        },
        async prtTaskUpdate(sn){
            this.currentIndex = parseInt(sn.substring(this.head.length))
            let res = await this.API.prtTaskUpdate({
                id:this.id,
                deviceSn:sn,
                currentIndex:sn.substring(this.head.length),
            })
        },
        continuePrintBatch(){
            let sn = ''
            let num = ''
            if(this.type == 2){
                if(!this.legal){
                    this.comm.showMsg(false,'请输入合法的标识头(SN长度不得大于12小于10)')
                    return
                }
            }
            if(this.currentIndex == parseInt(this.end)){
                this.headerMsg.finishFlag = 1
                this.$confirm('检测到当前任务以完成，是否继续当前任务进行下一步打印',{
                        closeOnClickModal:false
                    })
                .then(_ => {
                    try{
                        this.start = this.returnStringNum(parseInt(this.end)+1)
                        this.end = ''
                    } catch(err){
                        
                    }
                })
                .catch(async _ => {
                    this.prtTaskDelete()
                });
                this.continuePrintFlag = false
                this.batchFlag = false
                return
            }
            if(this.currentIndex > parseInt(this.end)){
                this.comm.showMsg(false,'当前打印位置不在sn起始范围内，请检查sn的起始范围！')
                return
            }
            if(!this.partNoFlag){
                this.comm.showMsg(false,'请先连接打印机')
                return
            }
            if(this.currentIndex){
                num = parseInt(this.currentIndex)+1
                sn = this.head + this.returnStringNum(num)
            }else{
                sn = this.head + this.start
            }
            if(this.typeSub == 1){
                this.typeBarQRBatch(sn)
            }else if(this.typeSub == 2){
                this.BarQRBatch(sn)
            }else if(this.typeSub == 3){
                this.BarBatch(sn)
            }
        },
        continuePrint(){
            let sn = ''
            let num = ''
            if(this.type == 2){
                if(!this.legal){
                    this.comm.showMsg(false,'请输入合法的标识头(SN长度不得大于12小于10)')
                    return
                }
            }
            if(this.currentIndex == this.headerMsg.endIndex){
                this.headerMsg.finishFlag = 1
                this.$confirm('检测到当前任务以完成，是否继续当前任务进行下一步打印',{
                        closeOnClickModal:false
                    })
                .then(_ => {
                    try{
                        this.start = this.returnStringNum(this.headerMsg.endIndex+1)
                        this.end = ''
                    } catch(err){
                        
                    }
                })
                .catch(async _ => {
                    this.prtTaskDelete()
                });
                this.continuePrintFlag = false
                return
            }
            if(this.currentIndex > parseInt(this.end)){
                this.comm.showMsg(false,'当前打印位置不在sn起始范围内，请检查sn的起始范围！')
                return
            }
            if(!this.partNoFlag){
                this.comm.showMsg(false,'请先连接打印机')
                return
            }
            if(this.currentIndex){
                num = parseInt(this.currentIndex)+1
                sn = this.head + this.returnStringNum(num)
            }else{
                sn = this.head + this.start
            }
            
            
            this.disabledFlag = true
            if(this.typeSub == 1){
                this.typeBarQR(sn)
            }else if(this.typeSub == 2){
                this.BarQR(sn)
            }else if(this.typeSub == 3){
                this.Bar(sn)
            }
        },
        async prtTaskSaveBatch(){

            let res = await this.API.prtTaskSave({
                prefix:this.head,
                startIndex:this.start,
                endIndex:this.end,
                printType:this.typeSub,
                superType:this.deviceType,
                deviceType:this.comm.returnCode(this.inverterTypeList,this.inverterTypeSet,'code','value'),
            })
            if(res.code == 1){
                if(this.headerMsg&&this.headerMsg.finishFlag == 0){
                    this.$confirm('检测到有未完成的任务，且当前任务与之冲突，是否继续未完成任务？',{
                        closeOnClickModal:false
                    })
                    .then(_ => {
                        try{
                            this.continuePrintFlag = true
                            this.batchFlag = false
                            this.start = this.returnStringNum(this.headerMsg.startIndex)
                            this.end = this.returnStringNum(this.headerMsg.endIndex)
                            let sn = ''
                            let num = ''
                            if(this.currentIndex){
                                num = parseInt(this.currentIndex)+1
                                sn = this.head + this.returnStringNum(num)
                            }else{
                                sn = this.head + this.start
                            }
                            if(this.typeSub == 1){
                                this.typeBarQR(sn)
                            }else if(this.typeSub == 2){
                                this.BarQR(sn)
                            }else if(this.typeSub == 3){
                                this.Bar(sn)
                            }
                        } catch(err){

                        }
                    })
                    .catch(async _ => {
                        this.prtTaskDelete()
                    });
                }else{
                    this.batchFlag = false
                    this.$confirm('任务重复或冲突，请检查SN范围！',{
                        closeOnClickModal:false
                    })
                    .then(_ => {
                        try{

                        } catch(err){
                            
                        }
                    })
                    .catch(async _ => {
                        this.prtTaskDelete()
                    });

                }
            }else if(res.code == 2){
                this.batchFlag = false
                this.comm.showMsg(false,'操作失败')
            }else if(res.code == 0){
                let res2 = await this.API.prtTaskGetNewestTask({
                    prefix:this.head.toUpperCase()
                })
                this.headerMsg = res2
                this.currentIndex = res2.currentIndex
                this.continuePrintFlag = true
                this.id = res2.sid
                let sn = ''
                let num = ''
                if(this.currentIndex){
                    num = parseInt(this.currentIndex)+1
                    sn = this.head + this.returnStringNum(num)
                }else{
                    sn = this.head + this.start
                }
                if(this.typeSub == 1){
                    this.typeBarQRBatch(sn)
                }else if(this.typeSub == 2){
                    this.BarQRBatch(sn)
                }else if(this.typeSub == 3){
                    this.BarBatch(sn)
                }
            }else{
                this.comm.showMsg(false,'程序发送未知错误，请联系管理员！')
            }
        },
        async prtTaskSave(){
            let res = await this.API.prtTaskSave({
                prefix:this.head,
                startIndex:this.start,
                endIndex:this.end,
                printType:this.typeSub,
                superType:this.deviceType,
                deviceType:this.comm.returnCode(this.inverterTypeList,this.inverterTypeSet,'code','value'),
            })
            if(res.code == 1){
                if(this.headerMsg&&this.headerMsg.finishFlag == 0){
                    this.$confirm('检测到有未完成的任务，且当前任务与之冲突，是否继续未完成任务？',{
                        closeOnClickModal:false
                    })
                    .then(_ => {
                        try{
                            this.continuePrintFlag = true
                            this.start = this.returnStringNum(this.headerMsg.startIndex)
                            this.end = this.returnStringNum(this.headerMsg.endIndex)
                            let sn = ''
                            let num = ''
                            if(this.currentIndex){
                                num = parseInt(this.currentIndex)+1
                                sn = this.head + this.returnStringNum(num)
                            }else{
                                sn = this.head + this.start
                            }
                            if(this.typeSub == 1){
                                this.typeBarQR(sn)
                            }else if(this.typeSub == 2){
                                this.BarQR(sn)
                            }else if(this.typeSub == 3){
                                this.Bar(sn)
                            }
                        } catch(err){
                            
                        }
                    })
                    .catch(async _ => {
                        this.prtTaskDelete()
                    });
                }else{
                    this.$confirm('任务重复或冲突，请检查SN范围！',{
                        closeOnClickModal:false
                    })
                    .then(_ => {
                        try{} catch(err){}
                    })
                    .catch(async _ => {
                        this.prtTaskDelete()
                    });
                }
            }else if(res.code == 2){
                this.comm.showMsg(false,'操作失败')
            }else if(res.code == 0){
                let res2 = await this.API.prtTaskGetNewestTask({
                    prefix:this.head.toUpperCase()
                })
                this.headerMsg = res2
                this.currentIndex = res2.currentIndex
                this.continuePrintFlag = true
                this.id = res2.sid
                let sn = ''
                let num = ''
                if(this.currentIndex){
                    num = parseInt(this.currentIndex)+1
                    sn = this.head + this.returnStringNum(num)
                }else{
                    sn = this.head + this.start
                }
                if(this.typeSub == 1){
                    this.typeBarQR(sn)
                }else if(this.typeSub == 2){
                    this.BarQR(sn)
                }else if(this.typeSub == 3){
                    this.Bar(sn)
                }
            }
        },
        async prtTaskGetNewestTask(){
            if(!this.head){
                return
            }
            let res = await this.API.prtTaskGetNewestTask({
                prefix:this.head.toUpperCase()
            })
            this.headerMsg = res
            if(res){
                this.headerMsg = res
                this.currentIndex = res.currentIndex
                this.id = res.sid
                if(res.finishFlag == 0){
                    
                    this.$confirm('检测到有未完成的任务，是否继续之前任务打印',{
                        closeOnClickModal:false
                    })
                    .then(() => {
                        try 
                        {    
                            this.start = this.returnStringNum(res.startIndex)
                            this.end = this.returnStringNum(res.endIndex)
                            this.continuePrintFlag = true
                            let sn = ''
                            let num = ''
                            
                            if(this.currentIndex){
                                console.log(this.currentIndex,'this.currentIndex');
                                num = parseInt(this.currentIndex)+1
                                sn = this.head + this.returnStringNum(num)
                            }else{
                                sn = this.head + this.start
                            }
                            if(this.typeSub == 1){
                                this.typeBarQR(sn)
                            }else if(this.typeSub == 2){
                                this.BarQR(sn)
                            }else if(this.typeSub == 3){
                                this.Bar(sn)
                            }
                        }catch(err)
                        {
                            console.log(err,'try-err')
                        }
                    })
                    .catch(() => {
                        this.prtTaskDelete()
                    });
                }else{
                    this.$confirm(`当前序列打印到${res.endIndex},是否继续打印？`,{
                        closeOnClickModal:false
                    })
                    .then(_ => {
                        try{
                            this.start = this.returnStringNum(res.endIndex+1)
                            this.continuePrintFlag = false
                            this.end = ''
                        } catch(err){
                            
                        }
                    })
                    .catch(async _ => {
                        this.prtTaskDelete()
                    });
                }
            }else{
                this.currentIndex = ''
            }
        },
        changeTypeSub(){
            this.continuePrintFlag = false
            this.returnInverterData()
            this.inverterType = ''
            this.head = ''
            this.end = ''
            this.start = ''
            this.currentIndex = ''
            this.id = ''
            this.headerMsg = {}
        },
        typeChange(){
            this.partNoFlag = false
            this.status  = "未连接";
            localStorage.setItem('printType',this.type)
            this.inverterType = ''
            this.typeSub = ''
            this.continuePrintFlag = false
            this.head = ''
            this.end = ''
            this.start = ''
            this.currentIndex = ''
            this.id = ''
            this.headerMsg = {}
        },
        async inverterTypeChange(){
            this.partNoFlag = false
            this.status  = "未连接";
            this.continuePrintFlag = false
            this.head = ''
            this.end = ''
            this.start = ''
            this.currentIndex = ''
            this.id = ''
            this.headerMsg = {}
            // let res = await this.API.prtsettingGetPage({
            //     partNo:this.inverterType,
            //     type:'',
            //     inverterType:'',
            //     size:10,
            //     current:1
            // })
            // if(res.rows.length==0 && this.typeSub == '1'){
            //     this.$confirm('检测到当前料号没有匹配逆变器机型，是否前往设置')
            //     .then(_ => {
            //         this.$emit("update:pageFlag",true)
            //         this.$store.commit('setPrintPartNo',this.inverterType)
            //     })
            //     .catch(_ => {
            //         this.partNoDisabled = true

            //     });
            // }else{
            //     this.inverterTypeSet = res.rows[0].inverterType
            //     this.partNoDisabled = false
            // }
            if(this.inverterType){
                this.inverterTypeSet = this.comm.returnCode(this.partList,this.inverterType,'partNo','inverterType')
            }
        },
        returnInverterData(){
            if(this.typeSub){
                let arr = []
                this.inverterTypeList.forEach(item=>{
                    if((parseInt(item.remark)+1) == this.typeSub){
                        arr.push(item)
                    }
                })
                this.inverterTypeData = arr
            }
        },
        blurEnd(){

            let numEnd = parseInt(this.end)
            let numStart = parseInt(this.start)

            if(this.headerMsg){
                if(this.headerMsg.endIndex == numEnd){
                    this.continuePrintFlag = true
                }else{
                    this.continuePrintFlag = false
                }
            }

            if(numEnd < numStart){
                this.comm.showMsg(false,'结束范围不得小于起始范围')
                this.end = ''
                return
            }
            if(this.end && this.head){
                let n = ''
                n = 14-this.head.length
                this.end = this.returnStringNum(this.end,n)
            }
        },
        blurStart(){
            let numEnd = parseInt(this.end)
            let numStart = parseInt(this.start)

            if(this.headerMsg){
                if(this.headerMsg.startIndex == numStart){
                    this.continuePrintFlag = true
                }else{
                    this.continuePrintFlag = false
                }
            }

            if(numEnd <= numStart){
                this.comm.showMsg(false,'起始范围不得大于或等于结束范围')
                this.start = ''
                return
            }
            if(this.start && this.head){
                this.start = this.returnStringNum(this.start)
            }
        },
        blurHead(){
            this.continuePrintFlag = false
            this.blurStart()
            this.blurEnd()
            if(this.head){
                if(this.head.length>13 || this.head.length<10){
                    this.legal = false
                    this.comm.showMsg(false,'请输入合法的标识头(长度不得大于12小于10)')
                    return
                }else{
                    this.legal = true
                }
            }
            this.prtTaskGetNewestTask()
        },
        returnStringNum(num){
            let n = ''
            n = 14-this.head.length
            return (Array(n).join(0) + num).slice(-n);
        },
        async getDictionaryBatch(){
            let res = await this.API.getDictionaryBatch({
                dictCodes:'WIFI_PART_NUM,INVERTER_TYPES,PRT_DEVICE_TYPES',
                lang:localStorage.getItem('lan') || 'zh_CN'
            })
            this.textDataList = res.WIFI_PART_NUM || []
            this.inverterTypeList = res.INVERTER_TYPES || []
            this.deviceTypeList = res.PRT_DEVICE_TYPES || []
        },
        connectPrint(csPrintFlag){
            if(!csPrintFlag){
                if(this.type == 2){
                    if(this.typeSub == '' ){
                        this.comm.showMsg(false,'请先选择打印类型')
                        return 
                    }
                    if(this.inverterType == '' && this.typeSub == 1){
                        this.comm.showMsg(false,'请先选择机型')
                        return 
                    }
                    if(this.head == '' ){
                        this.comm.showMsg(false,'请先填写SN标识头')
                        return 
                    }
                    if(this.start == '' ){
                        this.comm.showMsg(false,'请先填写起始范围')
                        return 
                    }
                    if(this.end == '' ){
                        this.comm.showMsg(false,'请先结束范围')
                        return 
                    }
                    
                }
            }
            
            if(this.type == 1){
                if(this.barType == ''){
                    this.comm.showMsg(false,'请先选择打印类型')
                    return 
                }
                if(this.partNo == ''){
                    this.comm.showMsg(false,'请先选择料号')
                    return 
                }
            }
            if ('WebSocket' in window) {
                ws = new WebSocket(wsUrl);
            } else if ('MozWebSocket' in window) {
                ws = new MozWebSocket(wsUrl);
            } else {
                this.comm.showMsg(false,'当前浏览器不支持')
            }
            let that = this
            ws.onopen = function() {
                that.comm.showMsg(true,'连接打印后台成功')
                that.status = '连接成功'
                that.partNoFlag = true
            }
            ws.onclose = function() {
                that.status = '连接失败'
                // that.comm.showMsg(false,'连接失败')
            }
            ws.onerror = function() {
                that.status = '数据传输发生错误'
                that.comm.showMsg(false,'数据传输发生错误,连接失败')
            }
            ws.onmessage = function(receiveMsg) {
                if (receiveMsg.data.split("|")[0] == "B_GetPrinterStatus") {
                    var ret = receiveMsg.data.split("|")[1];
                    if (ret == 2) {
                        that.status  = "2:USB端口开启失败";
                        return;
                    } else if (ret == 7) {
                        that.status  = "7:纸张/碳带用完！";
                        return;
                    } else if (ret == 4) {
                        that.status  = "4:内存溢出！"; //4:内存溢出！
                        return;
                    } else if (ret == 4) {
                        that.status  = "4 碳带用完或安装错误！"; //碳带用完或安装错误！";
                        return;
                    } else if (ret == 3) {
                        that.status  = "3:条码格式错误！"; //3:条码格式错误！";
                        return;
                    } else if (ret == 1) {
                        that.status  = "1:打印命令错误！"; //1:打印命令错误！
                        return;
                    } else if (ret == 6) {
                        that.status  = "6:串口通信异常！"; //6:串口通信异常！
                        return;
                    } else if (ret == 50) {
                        that.status  = "50:打印机忙碌！"; //50:打印机忙碌！  
                        return;
                    } else if (ret == 12) {
                        that.status  = "12:打印机暂停！"; //12:打印机暂停
                        return;
                    } else if (ret == 9) {
                        that.status  = "9:未取得返回值"; //9:未取得返回值
                        return;
                    } else if (ret == 0) {
                        that.status  = "0:等待列印!"; //0:等待列印!
                        return;
                    }
                }
            }
        },
        async printBatch(){
            
            if(this.partNo == '' && this.type == 1){
                this.comm.showMsg(false,'请先选择料号')
                return 
            }
            if(this.disabledFlag){
                return
            }
            if(!this.partNoFlag){
                this.comm.showMsg(false,'请先连接打印机')
                return
            }
            if(this.type==1){
                this.disabledFlag = true
                let res = await this.API.snGetBurnSn({
                    partNo : this.partNo,
                    num:1
                })
                setTimeout(()=>{
                    this.disabledFlag = false
                },800)
                if(res && res.object){
                    this.count = res.object.count
                    this.one(res.object.list)
                }else{
                    this.comm.showMsg(false,'未获取到SN')
                }
            }
            if(this.type==2){
                if(!this.legal){
                    this.comm.showMsg(false,'请输入合法的标识头(SN长度不得大于12小于10)')
                    return
                }
                if(this.start == '' ){
                    this.comm.showMsg(false,'请先填写起始范围')
                    return 
                }
                if(this.end == '' ){
                    this.comm.showMsg(false,'请先结束范围')
                    return 
                }
                this.batchFlag = true
                if(this.continuePrintFlag){
                    this.continuePrintBatch()
                    return
                }
                this.prtTaskSaveBatch()
            }
        },
        stopBatch(){
            window.clearTimeout(this.timeId)
            this.batchFlag = false
        },
        async print(){
            if(this.type == 1){
                if(this.barType == ''){
                    this.comm.showMsg(false,'请先选择打印类型')
                    return 
                }
                if(this.partNo == ''){
                    this.comm.showMsg(false,'请先选择料号')
                    return 
                }
            }
            if(this.disabledFlag){
                return
            }
            if(!this.partNoFlag){
                this.comm.showMsg(false,'请先连接打印机')
                return
            }
            if(this.type==1){
                this.disabledFlag = true
                let res = await this.API.snGetBurnSn({
                    partNo : this.partNo,
                    num:1
                })
                setTimeout(()=>{
                    this.disabledFlag = false
                },800)
                if(res && res.object){
                    this.count = res.object.count
                    if(this.barType == 1){
                        this.one(res.object.list)
                    }
                    if(this.barType == 2){
                        this.qbOne2or3(res.object.list,2)
                    }
                    if(this.barType == 3){
                        this.qbOne2or3(res.object.list,3)
                    }
                }else{
                    this.comm.showMsg(false,'未获取到SN')
                }
            }
            if(this.type==2){
                if(!this.legal){
                    this.comm.showMsg(false,'请输入合法的标识头(SN长度不得大于12小于10)')
                    return
                }
                if(this.start == '' ){
                    this.comm.showMsg(false,'请先填写起始范围')
                    return 
                }
                if(this.end == '' ){
                    this.comm.showMsg(false,'请先结束范围')
                    return 
                }
                this.prtTaskSave()
            }
        },
        typeBarQRBatch(sn){
            // VUE_APP_DOWNLOAD_PRINTSN
            
            let width = 0
            let url1 = process.env.VUE_APP_DOWNLOAD_PRINTSN+'/#/installationGuide?sn='+sn
            let url2 = 'www.solaxcloud.com/i18n/language.do?language=zh_CN&url=/views/installationGuide/index.jsp'
            ws.send('B_EnumUSB');
            ws.send('B_CreateUSBPort|1');
            ws.send('B_Set_Direction|B')
            ws.send(`B_Prn_Text_TrueType_W|${5+width}|30|42|10|微软雅黑|1|700|0|0|0|type|${this.inverterTypeSet}`);
            ws.send(`B_Prn_Text_TrueType_W|${5+width}|80|42|11|微软雅黑|1|700|0|0|0|type2|${this.inverterType}`);
            ws.send(`B_Prn_Barcode|${210+width}|30|0|1|2|2|80|N|${sn}`);
            ws.send(`B_Prn_Text_TrueType_W|${260+width}|115|39|12|微软雅黑|1|600|0|0|0|SN|${sn}`);
            ws.send(`B_Bar2d_QR|570|30|2|3|M|A|0|0|0|${url1}`);
            ws.send('B_Print_Out|1');
            ws.send('B_ClosePrn');
            let that = this
            ws.onmessage = function(receiveMsg) {
                if (receiveMsg.data.split("|")[0] == "B_Print_Out") {
                    var ret = receiveMsg.data.split("|")[1];
                    let obj={
                        sn:sn,
                        status:'file'
                    }
                    if (ret == 0) {
                        that.status  = "等待列印!"; //0:等待列印!
                        obj={
                            sn:sn,
                            status:'success'
                        }
                        that.printHistory.unshift(obj)
                        that.prtTaskUpdate(sn)
                        // that.currentIndex = parseInt(that.currentIndex)+1
                    }else{
                        that.status  = "打印失败";
                        that.printHistory.unshift(obj)
                        that.prtTaskUpdate(sn)
                        // that.prtTaskUpdate(sn) //为了方便测试暂时打开
                    }
                    window.clearTimeout(that.timeId)
                    that.timeId = window.setTimeout(()=>{
                        if(that.batchFlag){
                            that.continuePrintBatch()
                        }else{
                           window.clearTimeout(that.timeId) 
                        }
                    },800)
                }
            }
        },
        BarQRBatch(sn){
            let width = 0
            ws.send('B_EnumUSB');
            ws.send('B_CreateUSBPort|1');
            ws.send('B_Set_Direction|B')
            // ws.send(`B_Prn_Text_TrueType_W|${25+width}|65|42|12|微软雅黑|1|700|0|0|0|type|${this.inverterType}`);
            ws.send(`B_Prn_Barcode|${25+width}|30|0|1|2|2|80|N|${sn}`);
            // ws.send(`B_Prn_Text|${275+width}|115|0|2|1|1|N|H4602208093001`);
            ws.send(`B_Prn_Text_TrueType_W|${60+width}|115|39|13|微软雅黑|1|600|0|0|0|SN|${sn}`);
            ws.send(`B_Bar2d_QR|245|25|2|3|M|A|0|0|0|www.solaxcloud.com/#/installationGuide?sn=${sn}`);
            ws.send('B_Print_Out|1');
            ws.send('B_ClosePrn');
            let that = this
            ws.onmessage = function(receiveMsg) {
                if (receiveMsg.data.split("|")[0] == "B_Print_Out") {
                    var ret = receiveMsg.data.split("|")[1];
                    let obj={
                        sn:sn,
                        status:'file'
                    }
                    if (ret == 0) {
                        that.status  = "等待列印!"; //0:等待列印!
                        obj={
                            sn:arr[0],
                            status:'success'
                        }
                        that.printHistory.unshift(obj)
                        that.prtTaskUpdate(sn)
                        // that.currentIndex = parseInt(that.currentIndex)+1
                    }else{
                        that.status  = "打印失败";
                        // that.printHistory.unshift(obj)
                        // that.prtTaskUpdate(sn) //为了方便测试暂时打开
                    }
                    window.clearTimeout(this.timeId)
                    that.timeId = window.setTimeout(()=>{
                        if(that.batchFlag){
                            that.continuePrintBatch()
                        }
                    },800)
                }
            }
        },
        BarBatch(sn){
            let width = 0
            ws.send('B_EnumUSB');
            ws.send('B_CreateUSBPort|1');
            ws.send('B_Set_Direction|B')
            // ws.send(`B_Prn_Text_TrueType_W|${25+width}|65|42|12|微软雅黑|1|700|0|0|0|type|${this.inverterType}`);
            ws.send(`B_Prn_Barcode|${40+width}|30|0|1|2|2|80|N|${sn}`);
            // ws.send(`B_Prn_Text|${275+width}|115|0|2|1|1|N|H4602208093001`);
            ws.send(`B_Prn_Text_TrueType_W|${75+width}|115|39|13|微软雅黑|1|600|0|0|0|SN|${sn}`);
            // ws.send(`B_Bar2d_QR|220|25|2|3|M|A|0|0|0|www.solaxcloud.com/i18n/language.do?language=zh_CN&url=/views/installationGuide/index.jsp&sn=${sn}`);
            ws.send('B_Print_Out|1');
            ws.send('B_ClosePrn');
            let that = this
            ws.onmessage = function(receiveMsg) {
                if (receiveMsg.data.split("|")[0] == "B_Print_Out") {
                    var ret = receiveMsg.data.split("|")[1];
                    let obj={
                        sn:sn,
                        status:'file'
                    }
                    if (ret == 0) {
                        that.status  = "等待列印!"; //0:等待列印!
                        obj={
                            sn:arr[0],
                            status:'success'
                        }
                        that.printHistory.unshift(obj)
                        // that.currentIndex = parseInt(that.currentIndex)+1
                        that.prtTaskUpdate(sn)
                    }else{
                        that.status  = "打印失败";
                        that.printHistory.unshift(obj) 
                        // that.prtTaskUpdate(sn)//为了方便测试暂时打开
                    }
                    
                    window.clearTimeout(this.timeId)
                    that.timeId = window.setTimeout(()=>{
                        if(that.batchFlag){
                            that.continuePrintBatch()
                        }
                    },800)
                }
            }
        },
        typeBarQR(sn,csFlag){
            // VUE_APP_DOWNLOAD_PRINTSN
            
            let width = 0
            let url1 = process.env.VUE_APP_DOWNLOAD_PRINTSN+'/#/installationGuide?sn='+sn
            let url2 = 'www.solaxcloud.com/i18n/language.do?language=zh_CN&url=/views/installationGuide/index.jsp'
            ws.send('B_EnumUSB');
            ws.send('B_CreateUSBPort|1');
            ws.send('B_Set_Direction|B')
            ws.send(`B_Prn_Text_TrueType_W|${5+width}|30|42|10|微软雅黑|1|700|0|0|0|type|${csFlag ?this.comm.returnCode(this.partList,this.csPrintFormData.partNo,'partNo','inverterType'):this.inverterTypeSet}`);
            ws.send(`B_Prn_Text_TrueType_W|${5+width}|80|42|11|微软雅黑|1|700|0|0|0|type2|${csFlag ? this.csPrintFormData.partNo:this.inverterType}`);
            ws.send(`B_Prn_Barcode|${210+width}|30|0|1|2|2|80|N|${sn}`);
            ws.send(`B_Prn_Text_TrueType_W|${260+width}|115|39|12|微软雅黑|1|600|0|0|0|SN|${sn}`);
            ws.send(`B_Bar2d_QR|570|30|2|3|M|A|0|0|0|${url1}`);
            ws.send('B_Print_Out|1');
            ws.send('B_ClosePrn');
            let that = this
            ws.onmessage = function(receiveMsg) {
                if (receiveMsg.data.split("|")[0] == "B_Print_Out") {
                    var ret = receiveMsg.data.split("|")[1];
                    let obj={
                        sn:sn,
                        status:'file'
                    }
                    if (ret == 0) {
                        that.status  = "等待列印!"; //0:等待列印!
                        obj={
                            sn:sn,
                            status:'success'
                        }
                        that.printHistory.unshift(obj)
                        if(!csFlag){
                            that.prtTaskUpdate(sn)
                        }
                        // that.currentIndex = parseInt(that.currentIndex)+1
                    }else{
                        that.status  = "打印失败";
                        that.printHistory.unshift(obj)
                        if(!csFlag){
                            // that.prtTaskUpdate(sn)
                        }
                        // that.prtTaskUpdate(sn) //为了方便测试暂时打开
                    }
                    setTimeout(()=>{
                        that.disabledFlag = false
                    },800)
                }
            }
        },
        BarQR(sn,csFlag){
            let width = 0
            ws.send('B_EnumUSB');
            ws.send('B_CreateUSBPort|1');
            ws.send('B_Set_Direction|B')
            // ws.send(`B_Prn_Text_TrueType_W|${25+width}|65|42|12|微软雅黑|1|700|0|0|0|type|${this.inverterType}`);
            ws.send(`B_Prn_Barcode|${25+width}|30|0|1|2|2|80|N|${sn}`);
            // ws.send(`B_Prn_Text|${275+width}|115|0|2|1|1|N|H4602208093001`);
            ws.send(`B_Prn_Text_TrueType_W|${60+width}|115|39|13|微软雅黑|1|600|0|0|0|SN|${sn}`);
            ws.send(`B_Bar2d_QR|245|25|2|3|M|A|0|0|0|www.solaxcloud.com/#/installationGuide?sn=${sn}`);
            ws.send('B_Print_Out|1');
            ws.send('B_ClosePrn');
            let that = this
            ws.onmessage = function(receiveMsg) {
                if (receiveMsg.data.split("|")[0] == "B_Print_Out") {
                    var ret = receiveMsg.data.split("|")[1];
                    let obj={
                        sn:sn,
                        status:'file'
                    }
                    if (ret == 0) {
                        that.status  = "等待列印!"; //0:等待列印!
                        obj={
                            sn:arr[0],
                            status:'success'
                        }
                        that.printHistory.unshift(obj)
                        if(!csFlag){
                            that.prtTaskUpdate(sn)
                        }
                        // that.currentIndex = parseInt(that.currentIndex)+1
                    }else{
                        that.status  = "打印失败";
                        // that.printHistory.unshift(obj)
                        // that.prtTaskUpdate(sn) //为了方便测试暂时打开
                    }
                    setTimeout(()=>{
                        that.disabledFlag = false
                    },800)
                }
            }
        },
        Bar(sn,csFlag){
            let width = 0
            ws.send('B_EnumUSB');
            ws.send('B_CreateUSBPort|1');
            ws.send('B_Set_Direction|B')
            // ws.send(`B_Prn_Text_TrueType_W|${25+width}|65|42|12|微软雅黑|1|700|0|0|0|type|${this.inverterType}`);
            ws.send(`B_Prn_Barcode|${40+width}|30|0|1|2|2|80|N|${sn}`);
            // ws.send(`B_Prn_Text|${275+width}|115|0|2|1|1|N|H4602208093001`);
            ws.send(`B_Prn_Text_TrueType_W|${75+width}|115|39|13|微软雅黑|1|600|0|0|0|SN|${sn}`);
            // ws.send(`B_Bar2d_QR|220|25|2|3|M|A|0|0|0|www.solaxcloud.com/i18n/language.do?language=zh_CN&url=/views/installationGuide/index.jsp&sn=${sn}`);
            ws.send('B_Print_Out|1');
            ws.send('B_ClosePrn');
            let that = this
            ws.onmessage = function(receiveMsg) {
                if (receiveMsg.data.split("|")[0] == "B_Print_Out") {
                    var ret = receiveMsg.data.split("|")[1];
                    let obj={
                        sn:sn,
                        status:'file'
                    }
                    if (ret == 0) {
                        that.status  = "等待列印!"; //0:等待列印!
                        obj={
                            sn:arr[0],
                            status:'success'
                        }
                        that.printHistory.unshift(obj)
                        // that.currentIndex = parseInt(that.currentIndex)+1
                        if(!csFlag){
                            that.prtTaskUpdate(sn)
                        }
                    }else{
                        that.status  = "打印失败";
                        that.printHistory.unshift(obj) 
                        // that.prtTaskUpdate(sn)//为了方便测试暂时打开
                    }
                    
                    setTimeout(()=>{
                        that.disabledFlag = false
                    },800)
                }
            }
        },
        qbOne2or3(arr,type){
            let width = 294
            let	codex = 35
            let textx = 30
            if(type == 2){
                ws.send('B_EnumUSB');
                ws.send('B_CreateUSBPort|1');
                ws.send('B_Set_Direction|B')
                ws.send(`B_Prn_Text_TrueType_W|${4}|60|45|8|微软雅黑|1|600|0|0|0|SN|${arr[0]}`)
                ws.send(`B_Bar2d_QR|${149}|20|2|5|M|A|0|0|0|${arr[0]}`)

                ws.send(`B_Prn_Text_TrueType_W|${4+width}|60|45|8|微软雅黑|1|600|0|0|0|SN|${arr[0]}`)
                ws.send(`B_Bar2d_QR|${149+width}|20|2|5|M|A|0|0|0|${arr[0]}`)
                ws.send('B_Print_Out|1')
                ws.send('B_ClosePrn')
            }else if(type == 3){
                width = 240
                ws.send('B_EnumUSB');
                ws.send('B_CreateUSBPort|1');
                ws.send('B_Set_Direction|B')
                ws.send(`B_Prn_Text_TrueType_W|${2}|195|39|12|微软雅黑|1|600|0|0|0|SN|${arr[0]}`)
                ws.send(`B_Bar2d_QR|${5}|15|2|8|M|A|0|0|0|${arr[0]}`)
                
                ws.send(`B_Prn_Text_TrueType_W|${2+width}|195|39|12|微软雅黑|1|600|0|0|0|SN|${arr[0]}`)
                ws.send(`B_Bar2d_QR|${5+width}|15|2|8|M|A|0|0|0|${arr[0]}`)
                
                ws.send('B_Print_Out|1')
                ws.send('B_ClosePrn')
            }
            // ws.send('B_EnumUSB');
            // ws.send('B_CreateUSBPort|1');
            // ws.send('B_Set_Direction|B')
            // ws.send(`B_Prn_Text_TrueType_W|${15}|60|39|12|微软雅黑|1|600|0|0|0|SN|${arr[0]}`)
            // ws.send(`B_Bar2d_QR|${205}|15|2|3|M|A|0|0|0|${arr[0]}`)

            // ws.send(`B_Prn_Text_TrueType_W|${15+width}|60|39|12|微软雅黑|1|600|0|0|0|SN|${arr[0]}`)
            // ws.send(`B_Bar2d_QR|${205+width}|15|2|3|M|A|0|0|0|${arr[0]}`)
            // ws.send('B_Print_Out|1')
            // ws.send('B_ClosePrn')
            let that = this
            ws.onmessage = function(receiveMsg) {
                if (receiveMsg.data.split("|")[0] == "B_Print_Out") {
                    var ret = receiveMsg.data.split("|")[1];
                    let obj={
                        sn:arr[0],
                        status:'file'
                    }
                    if (ret == 0) {
                        that.status  = "等待列印!"; //0:等待列印!
                        obj={
                            sn:arr[0],
                            status:'success'
                        }
                        that.printHistory.unshift(obj)
                        return;
                    }else{
                        that.status  = "打印失败";
                        that.printHistory.unshift(obj)
                    }

                }
            }
        },
        one(arr){
            let width = 260
            let	codex = 35
            let textx = 30
            if(arr[0].length == 16) {
                codex = 25
                textx = 20
                width = 200
            }
            if(arr[0].length == 8) {
                codex = 60
                textx = 55
                width = 270
            }
            ws.send('B_EnumUSB');
            ws.send('B_CreateUSBPort|1');
            ws.send('B_Set_Direction|B')
            ws.send(`B_Prn_Barcode|${codex}|20|0|1|1|2|40|N|${arr[0]}`)
            ws.send(`B_Prn_Text|${textx}|60|0|2|1|1|N|${arr[0]}`)

            ws.send(`B_Prn_Barcode|${codex+width}|20|0|1|1|2|40|N|${arr[0]}`)
            ws.send(`B_Prn_Text|${textx+width}|60|0|2|1|1|N|${arr[0]}`)
            ws.send('B_Print_Out|1')
            ws.send('B_ClosePrn')
            let that = this
            ws.onmessage = function(receiveMsg) {
                if (receiveMsg.data.split("|")[0] == "B_Print_Out") {
                    var ret = receiveMsg.data.split("|")[1];
                    let obj={
                        sn:arr[0],
                        status:'file'
                    }
                    if (ret == 0) {
                        that.status  = "等待列印!"; //0:等待列印!
                        obj={
                            sn:arr[0],
                            status:'success'
                        }
                        that.printHistory.unshift(obj)
                        return;
                    }else{
                        that.status  = "打印失败";
                        that.printHistory.unshift(obj)
                    }

                }
            }
        }
        
    },
};
</script>

<style  lang="less">
.print-sn-main-box{
    .massage-box{
        margin-bottom: 10px;
        color: #fea429;
        span:nth-child(2n){
            margin-right:15px;
        }
    }
    .content-main-box{
        .el-card__header{
            padding: 10px 20px;
        }
        .content-header{
            text-align: center;
            font-size: 25px;
            font-weight: 900;
            border-bottom: 1px dashed #ccc;
            margin-bottom: 15px;
        }
        .content-box{
            height:350px;
            overflow-y: scroll;
            width: calc(100% + 40px);
        }
        .red{
            color: red;
            span{
                color: red;
            }
        }
    }
}
</style>
